package com.douyu.ocean.recom.platfrom.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.spring.AnnotationBean;
import com.douyu.ocean.config.client.PropertiesConfigClient;
import com.douyu.ocean.config.entity.ClientConfigure;

@Configuration  
public class DubboConfig {

	/** dubbo服务提供应用名称 */
    private static final String APPLICATION_NAME = "ocean-recom-platform-provider";

    /** dubbo注解扫描包 */
    private static final String ANNOTATION_PACKAGE = "com.douyu.ocean.recom.platfrom.core.facade.impl";

    /** dubbo注册节点 */
    private static final String REGISTRY_GROUP = "dubbo/"+System.getProperty("app.mode","ocean");

    /** zookeeper客户端 */
    private static final String REGISTRY_CLIENT = "curator";

    /**
     * 配置Dubbo应用
     *
     * @return application config
     */
    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(APPLICATION_NAME);
        return applicationConfig;
    }

    /**
     * 注册Dubbo服务
     *
     * @return registry config
     */
    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setGroup(REGISTRY_GROUP);
        registryConfig.setClient(REGISTRY_CLIENT);
        registryConfig.setAddress(propertiesConfigClient().getRequiredString("dubbo.registry.address"));
        registryConfig.setProtocol("zookeeper");
        registryConfig.setCheck(Boolean.FALSE);
        return registryConfig;
    }

    /**
     * Protocol config protocol config.
     * 服务提供者的协议相关配置
     * @return the protocol config
     */
    @Bean
    public ProtocolConfig protocolConfig(){
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName("dubbo");
        //protocol.setSerialization("kryo");
        protocol.setPort(NetUtils.getAvailablePort());
        return protocol;
    }

    /**
     * 配置Dubbo注解包扫描路径
     *
     * @return annotation bean
     */
    @Bean
    public AnnotationBean annotationBean() {
        AnnotationBean annotationBean = new AnnotationBean();
        annotationBean.setPackage(ANNOTATION_PACKAGE);
        return annotationBean;
    }

    /**
     * 获取PropertiesConfigClient
     * @return
     */
    private PropertiesConfigClient propertiesConfigClient(){
        return new PropertiesConfigClient(new ClientConfigure(
                System.getProperty("app.mode","ocean"),
                "ocean-config-cache",
                "config"
        ));
    }
}
